package com.carlinfo.back.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.common.util.DateUtile;
import com.carlinfo.common.util.PageInfoUtil;
import com.carlinfo.demo.pojo.ADynasty;
import com.carlinfo.demo.pojo.AKing;
import com.carlinfo.demo.service.IDemoService;
import com.carlinfo.demo.service.impl.DemoServiceImpl;

public class DemoBackServlet extends HttpServlet
{
	
	private Logger logger = LogManager.getLogger();
	private DateUtile dateUtil = new DateUtile();

	/* 创建一个demoService */
	private IDemoService demoService = new DemoServiceImpl();

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		String method = request.getParameter("method");
		if ("dynastyList".equalsIgnoreCase(method))
		{
			dynastyList(request, response);
		} else if ("dynastyInsert".equalsIgnoreCase(method))
		{
			dynastyInsert(request, response);
		} else if ("dynastyInsertSubmit".equalsIgnoreCase(method))
		{
			dynastyInsertSubmit(request, response);
		} else if ("dynastyUpdate".equalsIgnoreCase(method))
		{
			dynastyUpdate(request, response);
		} else if ("dynastyUpdateSubmit".equalsIgnoreCase(method))
		{
			dynastyUpdateSubmit(request, response);
		} else if ("kingList".equalsIgnoreCase(method))
		{
			/**
			 * 皇上的操作如下
			 */
			kingList(request, response);
		} else if ("kingInsert".equalsIgnoreCase(method))
		{
			kingInsert(request, response);
		} else if ("kingInsertSubmit".equalsIgnoreCase(method))
		{
			kingInsertSubmit(request, response);
		} else if ("kingUpdate".equalsIgnoreCase(method))
		{
			kingUpdate(request, response);
		} else if ("kingUpdateSubmit".equalsIgnoreCase(method))
		{
			kingUpdateSubmit(request, response);
		}
	}

	/*
	 * 皇上的操作
	 */
	private void kingUpdateSubmit(HttpServletRequest request, HttpServletResponse response)
	{/* 问jsp要一个id */
		String id = request.getParameter("id");
		/* 存储的是查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 根据id查询 */
		condMap.put("id", id);
		// condMap.put("name", "大明");
		AKing king = this.demoService.selectOneKingService(condMap);
//		if (king != null)
//		{
		/* 全部修改 */
		/* 从jsp中获取 */
		/*
		 * String name = request.getParameter("name"); String capital =
		 * request.getParameter("capital"); String age = request.getParameter("age");
		 * String st = request.getParameter("st"); String pubTime =
		 * request.getParameter("pubTime"); String context =
		 * request.getParameter("context"); String status =
		 * request.getParameter("status");
		 * 
		 * king.setName(name); king.set.setCapital(capital); 420--->266:
		 * king.setAge(Integer.valueOf(age)); king.setContext(context); dateUtil
		 * king.setSt(this.dateUtil.strToDateTime(st));
		 * king.setPubTime(this.dateUtil.strToDateTime(pubTime));
		 * 
		 * king.setStatus(Byte.valueOf(status)); king.setUpdateTime(new Date()); 更新对象
		 * JSONObject resultJSON = this.demoService.updateOneKingService(king);
		 * System.out.println(resultJSON.toJSONString()); try {
		 * response.setContentType("text/html;charset=UTF-8"); PrintWriter writer =
		 * response.getWriter(); writer.println(resultJSON); writer.flush();
		 * writer.close(); } catch (IOException e) { e.printStackTrace(); }
		 * this.logger.info("返回值:{}", resultJSON); }
		 */
	}

	private void kingUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		this.logger.info("--DemoBackServlet--kingUpdate--");
		/* 问jsp要一个id */
		String id = request.getParameter("id");
		/* 存储的是查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 根据id查询 */
		condMap.put("id", id);
		AKing king = this.demoService.selectOneKingService(condMap);
		/* 赶紧将查询的结果放到四大作用域(request中) */
		request.setAttribute("king", king);
		String path = "/WEB-INF/jsp/back/demo/kingUpdate.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void kingInsertSubmit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/*
		 * String name = request.getParameter("name"); String capital =
		 * request.getParameter("capital"); String age = request.getParameter("age");
		 * String st = request.getParameter("st"); String pubTime =
		 * request.getParameter("pubTime"); String context =
		 * request.getParameter("context"); String status =
		 * request.getParameter("status");
		 * 
		 * // new出来的,属性有值? AKing king = new AKing(); king.setName(name);
		 * king.setCapital(capital); // 420--->266: king.setAge(Integer.valueOf(age));
		 * king.setContext(context); // dateUtil
		 * king.setSt(this.dateUtil.strToDateTime(st));
		 * king.setPubTime(this.dateUtil.strToDateTime(pubTime));
		 * 
		 * king.setStatus(Byte.valueOf(status)); king.setCreateTime(new Date());
		 * king.setUpdateTime(new Date());
		 * 
		 * // 保存一条记录 JSONObject resultJSON = this.demoService.saveOneKingService(king);
		 * this.logger.info("返回值:{}", resultJSON);
		 * 
		 * // 往request中放的是json request.setAttribute("resultJSON", resultJSON); //
		 * 保存成功,又跳转到朝代添加的jsp中 this.kingList(request, response);
		 */
	}

	private void kingInsert(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/demo/kingInsert.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void kingList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");

		/* 处理参数 */
		if (keyword == null)
		{
			keyword = "";
		}
		if (status == null)
		{
			status = "";
		}
		if (st == null)
		{
			st = "";
		}
		if (ed == null)
		{
			ed = "";
		}

//	PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/*
		 * 为了实现分页; 所需要的数据写活,问发信人的信里面要 取信的内容 ?a=1&b=2&c=3
		 */
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");

		/* 查询10条 */
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		try
		{
			/*
			 * 如果currentPage发信人木有传,就是null;知道会报, try一下,异常不打印
			 */
			/* 每页10条, */
			pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
			/* 第一页 */
			pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
		} catch (NumberFormatException e)
		{
		}
		/* 存储的是查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 按照关键字搜索 */
		condMap.put("keyword", keyword);
		/* 按照状态搜索 */
		condMap.put("status", status);
		/*
		 * 按照时间范围搜索 stDate:开始时间 edDate:结束时间 request.getParameter返回值是字符串;
		 * 但是时间搜索我们要的是时间类型; 将字符串变成时间类型
		 */
		Date edDate = null;
		Date stDate = null;
		if (!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			stDate = this.dateUtil.strToDateTime(st);
			edDate = this.dateUtil.strToDateTime(ed);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		// this.logger.info("{}----->{}",stDate.toLocaleString(),edDate.toLocaleString());

		/* 排序:必须是指定值 */
		// condMap.put("orderBy", "idAscNameDesc");
		/* 打开开关,查询关联关系 */
		condMap.put("extend", "true");

		List<AKing> kingList = this.demoService.selectListKingService(pageInfoUtil, condMap);
		/* 站在使用者的角度,不想分页,直接将pageInfoUtil传成null */
		// List<ADynasty> dynastyList =
		// this.demoService.selectListService(null,condMap);
		/*
		 * 所有在测试类中打印的代码统统放到jsp上面 数据的产生是在demoBackServlet中 数据的显示是在dynastyList中
		 * 他们两个可是不同的Servlet;如何将数据传过去呢? 四大作用域:page < request < session < application
		 * 原则:能用小的,别用大的;
		 * 
		 * 在任何地方,取数据的时候,一定要想三遍:我放了木有,我放了木有,我放了木有;
		 */
		request.setAttribute("kingList", kingList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		/* 将所有的搜索条件存储 */
		request.setAttribute("keyword", keyword);
		request.setAttribute("status", status);
		request.setAttribute("st", st);
		request.setAttribute("ed", ed);

		/*
		 * 服务器端跳转: 为啥要跳转:因为写html回信,jsp善长
		 */
		String path = "/WEB-INF/jsp/back/demo/kingList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	/*
	 * 朝代的操作
	 */
	private void dynastyUpdateSubmit(HttpServletRequest request, HttpServletResponse response)
	{/* 问jsp要一个id */
		String id = request.getParameter("id");
		/* 存储的是查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 根据id查询 */
		condMap.put("id", id);
		// condMap.put("name", "大明");
		ADynasty dynasty = this.demoService.selectOneDynastyService(condMap);
		if (dynasty != null)
		{
			/* 全部修改 */
			/* 从jsp中获取 */
			String name = request.getParameter("name");
			String capital = request.getParameter("capital");
			String age = request.getParameter("age");
			String st = request.getParameter("st");
			String pubTime = request.getParameter("pubTime");
			String context = request.getParameter("context");
			String status = request.getParameter("status");

			dynasty.setName(name);
			dynasty.setCapital(capital);
			/* 420--->266: */
			dynasty.setAge(Integer.valueOf(age));
			dynasty.setContext(context);
			/* dateUtil */
			dynasty.setSt(this.dateUtil.strToDateTime(st));
			dynasty.setPubTime(this.dateUtil.strToDateTime(pubTime));

			dynasty.setStatus(Byte.valueOf(status));
			dynasty.setUpdateTime(new Date());
			/* 更新对象 */
			JSONObject resultJSON = this.demoService.updateOneDynastyService(dynasty);
			System.out.println(resultJSON.toJSONString());
			try
			{
				response.setContentType("text/html;charset=UTF-8");
				PrintWriter writer = response.getWriter();
				writer.println(resultJSON);
				writer.flush();
				writer.close();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
			this.logger.info("返回值:{}", resultJSON);
		}
	}

	private void dynastyUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		this.logger.info("--DemoBackServlet--dynastyUpdate--");
		/* 问jsp要一个id */
		String id = request.getParameter("id");
		/* 存储的是查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 根据id查询 */
		condMap.put("id", id);
		ADynasty dynasty = this.demoService.selectOneDynastyService(condMap);
		/* 赶紧将查询的结果放到四大作用域(request中) */
		request.setAttribute("dynasty", dynasty);
		String path = "/WEB-INF/jsp/back/demo/dynastyUpdate.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void dynastyInsertSubmit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String name = request.getParameter("name");
		String capital = request.getParameter("capital");
		String age = request.getParameter("age");
		String st = request.getParameter("st");
		String pubTime = request.getParameter("pubTime");
		String context = request.getParameter("context");
		String status = request.getParameter("status");

		// new出来的,属性有值?
		ADynasty dynasty = new ADynasty();
		dynasty.setName(name);
		dynasty.setCapital(capital);
		// 420--->266:
		dynasty.setAge(Integer.valueOf(age));
		dynasty.setContext(context);
		// dateUtil
		dynasty.setSt(this.dateUtil.strToDateTime(st));
		dynasty.setPubTime(this.dateUtil.strToDateTime(pubTime));

		dynasty.setStatus(Byte.valueOf(status));
		dynasty.setCreateTime(new Date());
		dynasty.setUpdateTime(new Date());

		// 保存一条记录
		JSONObject resultJSON = this.demoService.saveOneDynastyService(dynasty);
		this.logger.info("返回值:{}", resultJSON);

		// 往request中放的是json
		request.setAttribute("resultJSON", resultJSON);
		// 保存成功,又跳转到朝代添加的jsp中
		this.dynastyList(request, response);
	}

	private void dynastyInsert(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/demo/dynastyInsert.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void dynastyList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		/* 从jsp中获取传过来的信 */
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		String stDate = request.getParameter("stDate");
		logger.info("-转之前->", stDate);
		String enDate = request.getParameter("enDate");
		if (keyword == null)
		{
			keyword = "";
		}
		if (status == null)
		{
			status = "";
		}
		if (stDate == null)
		{
			stDate = "";
		}
		if (enDate == null)
		{
			enDate = "";
		}
//		String 
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		try
		{
			/*
			 * 如果currentPage发信人木有传,就是null;知道会报, try一下,异常不打印
			 */
			/* 每页10条, */
			pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
			/* 第一页 */
			pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
		} catch (NumberFormatException e)
		{
		}
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyword", keyword);
		condMap.put("status", status);
//		Calendar calendar = Calendar.getInstance();
//		Date enDate = calendar.getTime();
//		calendar.add(calendar.MONTH, -1);
//		Date stDate = calendar.getTime();
		Date st = null;
		Date en = null;

		if (!"".equalsIgnoreCase(stDate) && !"".equalsIgnoreCase(enDate))
		{
			st = dateUtil.strToDateTime(stDate);
			en = dateUtil.strToDateTime(enDate);
		}
		logger.info("--转后--->{}", st);
		condMap.put("stDate", st);
		condMap.put("enDate", en);
//		pageInfoUtil.setCurrentPage(5);
//		pageInfoUtil.setPageSize(10);	
		List<ADynasty> dynastyList = demoService.selectListDynastyService(pageInfoUtil, condMap);
		request.setAttribute("dynastyList", dynastyList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		/* 往jsp中添加值 */
		request.setAttribute("keyword", keyword);
		request.setAttribute("status", status);
		request.setAttribute("stDate", stDate);
		request.setAttribute("enDate", enDate);
		/* 跳转的路径 */
		request.setAttribute("dynastyList", dynastyList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		String path = "/WEB-INF/jsp/back/demo/dynastyList.jsp";
		/* 跳转的方法 */
		request.getRequestDispatcher(path).forward(request, response);
	}

}
